package runner

import (
	"github.com/shima-park/agollo"
	"os"
	"strconv"
)

var (
	//defaultConfigFile = "config22.toml"
	DefaultRunner GRunner
)

type GRunner interface {
	Clear()
	GetEnv() *ServerEnv
}

type grunner struct {
	//opts Options
	env  *ServerEnv
}

func (g *grunner) Clear() {
//	g.opts.MySqlConn()
}

func (g *grunner) GetEnv() *ServerEnv {
	return g.env
}

func NewRunner() GRunner {
	g := &grunner{}
	no := agollo.Get(AppServerNo)
	name := agollo.Get(AppServerName)
	mode := agollo.Get(AppMode)
	ip := agollo.Get(AppIp)
	port := agollo.Get(AppPort)
	port_int, _ := strconv.Atoi(port)
	//options, err := newOptions(nodeNo, name, ip, port_int, mode, opts...)
	//if err != nil {
	//	return nil, err
	//}

	g.env = GetServerEnv().
		SetServerNo(no).
		SetServerName(name).
		SetIp(ip).
		SetPort(port_int).
		SetMode(mode)
	//g.opts = options
	return g
}


func InitWithApolloConfig() error {
	err := InitApollo()
	if err == nil {
		DefaultRunner = NewRunner()
	}
	return err
}

func InitApollo() error {
	err := agollo.InitWithDefaultConfigFile(
		agollo.WithLogger(agollo.NewLogger(agollo.LoggerWriter(os.Stdout))), // 打印日志信息
		//agollo.PreloadNamespaces("TEST.Namespace"),              // 预先加载的namespace列表，如果是通过配置启动，会在app.properties配置的基础上追加
		agollo.AutoFetchOnCacheMiss(),                                       // 在配置未找到时，去apollo的带缓存的获取配置接口，获取配置
		agollo.FailTolerantOnBackupExists(),                                 // 在连接apollo失败时，如果在配置的目录下存在.agollo备份配置，会读取备份在服务器无法连接的情况下
		agollo.DefaultNamespace("develop"),					// 默认的Namespace
	)

	return err
}